package features.advance.jdk.concurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LIN
 * @date 2022-03-16 22:22
 */
public class ReentrantLockTest {

    public static void main(String[] args) {

        new Thread(()->Solution.test(),"线程A").start();
        new Thread(()->Solution.test(),"线程B").start();
        new Thread(()->Solution.test(),"线程C").start();
        new Thread(()->Solution.test(),"线程D").start();
        new Thread(()->Solution.test(),"线程E").start();


    }

    static class Solution {
        private static final Lock lock = new ReentrantLock();
        public static void test(){
            try{
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"获取了锁");
                TimeUnit.SECONDS.sleep(2);
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                System.out.println(Thread.currentThread().getName()+"释放了锁");
                lock.unlock();
            }
        }
    }

    static class Solution1 {
        private static final Lock lock = new ReentrantLock(true);
        public static void test(){
            for (int i = 0; i < 2; i++) {
                try{
                    lock.lock();
                    System.out.println(Thread.currentThread().getName()+"获取了锁");
                    TimeUnit.SECONDS.sleep(2);
                }catch(Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }

        public static void main(String[] args) {
            new Thread(()->test(),"线程A").start();
            new Thread(()->test(),"线程B").start();
            new Thread(()->test(),"线程C").start();
            new Thread(()->test(),"线程D").start();
            new Thread(()->test(),"线程E").start();
        }
    }
}
